package com.learn.cloud.validator.constraints;

import com.learn.cloud.validator.annotation.GenderValidation;
import com.learn.cloud.validator.enums.GenderEnum;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

/**
 * @description: 性别校验，判断是否为GenderEnum中的值
 * @author: cong zhi
 * @createDate: 2022/2/6 12:42
 * @updateUser: cong zhi
 * @updateDate: 2022/2/6 12:42
 * @updateRemark: 修改内容
 * @version: v1.0
 */
public class GenderValidator implements ConstraintValidator<GenderValidation, Integer> {

    private Boolean required;

    @Override
    public void initialize(GenderValidation constraintAnnotation) {
        this.required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(Integer genderValue, ConstraintValidatorContext context) {
        // 如果是必填的
        if (required && null == genderValue) {
            return false;
        }
        // 如果不是必填,为空则通过
        if (!required && null == genderValue) {
            return true;
        }
        // 校验值是否是枚举中的值
        GenderEnum genderEnum = GenderEnum.codeToEnum(genderValue);
        return genderEnum != null;
    }
}
